import { GameMode } from "@minecraft/server";
import { BlockedInCombatModule } from "../module";
import { Dimensions } from "@sapi-game/constants";
import { BlockedRandomMapLoader } from "../components/mapLoader";
import { BlockedMainState } from "./mainState";
import { Game } from "@sapi-game/main";
import { Duration } from "@sapi-game/utils";
import { EffectIds } from "@sapi-game/utils/vanila-data";

export class BlockedLoadState extends BlockedInCombatModule.State {
    override onEnter(): void {
        this.initPlayer();
        this.addComponent(BlockedRandomMapLoader);
        //给药水效果
        this.subscribe(
            Game.events.interval,
            () => {
                this.context.groupSet.forEach((p) =>
                    p.addEffect(EffectIds.Resistance, 100, 255)
                );
            },
            new Duration(20)
        );
    }

    initPlayer() {
        this.context.groupSet.forEach((p) => {
            p.player.teleport(this.context.map.loadingPos);
            p.player.setSpawnPoint({
                dimension: Dimensions.Overworld,
                ...this.context.map.loadingPos,
            });
            p.player.setGameMode(GameMode.Adventure);
            p.clear();
            p.title("地图生成中...", this.context.map.name);
        });
    }

    stop(err: unknown) {
        this.logger.error("地图加载失败", err);
        this.engine.stopGame();
    }

    next() {
        this.transitionTo(BlockedMainState);
    }
}
